package com.study.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.app.domain.AppUserEmergency;
import com.study.app.domain.bo.AppUserEmergencyBo;
import com.study.app.domain.vo.AppUserEmergencyVo;
import com.study.app.mapper.AppUserEmergencyMapper;
import com.study.app.service.IAppUserEmergencyService;
import com.study.common.core.domain.PageQuery;
import com.study.common.core.page.TableDataInfo;
import com.study.common.utils.AesGcmUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 用户紧急联系人Service业务层处理
 *
 * @author magicyo
 * @date 2023-11-29
 */
@RequiredArgsConstructor
@Service
public class AppUserEmergencyServiceImpl implements IAppUserEmergencyService {

    private final AppUserEmergencyMapper baseMapper;

    /**
     * 查询用户紧急联系人
     */
    @Override
    public AppUserEmergencyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户紧急联系人列表
     */
    @Override
    public TableDataInfo<AppUserEmergencyVo> queryPageList(AppUserEmergencyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppUserEmergency> lqw = buildQueryWrapper(bo);
        Page<AppUserEmergencyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户紧急联系人列表
     */
    @Override
    public List<AppUserEmergencyVo> queryList(AppUserEmergencyBo bo) {
        LambdaQueryWrapper<AppUserEmergency> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppUserEmergency> buildQueryWrapper(AppUserEmergencyBo bo) {
        LambdaQueryWrapper<AppUserEmergency> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppUserEmergency::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), AppUserEmergency::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), AppUserEmergency::getPhone, bo.getPhone());
        return lqw;
    }

    /**
     * 新增用户紧急联系人
     */
    @Override
    public Boolean insertByBo(AppUserEmergencyBo bo) {
        AppUserEmergency add = BeanUtil.toBean(bo, AppUserEmergency.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户紧急联系人
     */
    @Override
    public Boolean updateByBo(AppUserEmergencyBo bo) {
        AppUserEmergency update = BeanUtil.toBean(bo, AppUserEmergency.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppUserEmergency entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户紧急联系人
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<AppUserEmergencyVo> queryListById(Long userId) {
        List<AppUserEmergencyVo> appUserEmergencyVos = baseMapper.selectVoList(new LambdaQueryWrapper<AppUserEmergency>()
                .eq(AppUserEmergency::getUserId, userId));
        for (AppUserEmergencyVo userEmergency:appUserEmergencyVos) {
            try {
                userEmergency.setName(AesGcmUtils.decrypt(userEmergency.getName()));
                userEmergency.setPhone(AesGcmUtils.decrypt(userEmergency.getPhone()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return appUserEmergencyVos;
    }

    @Override
    public Boolean userJudge(Long userId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<AppUserEmergency>()
                .eq(AppUserEmergency::getUserId, userId)) >= 2 ? true : false;
    }

    @Override
    public Boolean deleteUser(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    public Long getUserEmergency(Long userId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<AppUserEmergency>()
                .eq(AppUserEmergency::getUserId,userId));
    }
    /**
     * 获取当前用户紧急联系人信息
     * @param emergency
     * @return
     */
    @Override
    public AppUserEmergencyVo getUserEmergencyInfo(AppUserEmergency emergency) {
        AppUserEmergencyVo appUserEmergencyVo = baseMapper.selectVoOne(new LambdaQueryWrapper<AppUserEmergency>()
                .eq(StringUtils.isNotBlank(emergency.getUserId().toString()), AppUserEmergency::getUserId, emergency.getUserId())
                .last("limit 1"));
        return appUserEmergencyVo;
    }
}

